package com.uca.sisbec.helpers.becario;

import com.uca.sisbec.beans.CommentBean;
import com.uca.sisbec.mapping.Becario;
import com.uca.sisbec.mapping.Comentario;
import com.uca.sisbec.mapping.ComentarioId;
import com.uca.sisbec.mapping.Usuario;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.Query;
import org.hibernate.Session;

public class ComentarioHelper {
    private Session session;
    
    public ComentarioHelper(Session session){
        this.session = session;
    }

    public List<CommentBean> getCommentsByUser(HttpServletRequest request) {
        String carnet = ((Becario)request.getSession().getAttribute("_BECARIO")).getCarnet();
        String alias = ((Usuario)request.getSession().getAttribute("_USER")).getAlias();
        String hql = "select new com.uca.sisbec.beans.CommentBean "
                + "(id.idComentario, comentario, fecha) "
                + "from Comentario "
                + "where id.alias = :v_alias "
                + "and id.carnet = :v_carnet "
                + "order by fecha desc ";
        Query query = session.createQuery(hql);
        query.setString("v_alias", alias);
        query.setString("v_carnet", carnet);
        List<CommentBean> commentList = new ArrayList<CommentBean>(query.list());
        return commentList;
    }

    public void saveComment(String carnet, String alias, String comment) {
        Comentario comentario = new Comentario();
        ComentarioId id = new ComentarioId();
        id.setCarnet(carnet);
        id.setAlias(alias);
        comentario.setId(id);
        comentario.setComentario(comment);
        session.save(comentario);
    }

    public void deleteComment(int id) {
        String hql = "from Comentario where id.idComentario = :v_id";
        Query query = session.createQuery(hql);
        query.setInteger("v_id", id);
        Comentario comentario = (Comentario) query.uniqueResult();
        session.delete(comentario);
    }
}
